from flask import Flask, render_template, request, jsonify, redirect, url_for
from models import db, Student
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://mhw:0909@192.168.137.131/exam_work'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

@app.route('/')
def index():
    students = Student.query.all()
    return render_template('students.html', students=students)

@app.route('/student/add', methods=['POST'])
def add_student():
    try:
        data = request.form
        student = Student(
            Sno=data['Sno'],
            Sname=data['Sname'],
            Ssex=data['Ssex'],
            Sage=int(data['Sage']),
            Dno=data['Dno'],
            Sclass=data['Sclass'],
            address=data['address']
        )
        db.session.add(student)
        db.session.commit()
        return redirect(url_for('index'))
    except Exception as e:
        return jsonify({'error': str(e)}), 400

@app.route('/student/edit/<string:sno>', methods=['POST'])
def edit_student(sno):
    try:
        student = Student.query.get_or_404(sno)
        data = request.form
        
        student.Sname = data['Sname']
        student.Ssex = data['Ssex']
        student.Sage = int(data['Sage'])
        student.Dno = data['Dno']
        student.Sclass = data['Sclass']
        student.address = data['address']
        
        db.session.commit()
        return redirect(url_for('index'))
    except Exception as e:
        return jsonify({'error': str(e)}), 400

@app.route('/student/delete/<string:sno>', methods=['POST'])
def delete_student(sno):
    try:
        student = Student.query.get_or_404(sno)
        db.session.delete(student)
        db.session.commit()
        return redirect(url_for('index'))
    except Exception as e:
        return jsonify({'error': str(e)}), 400

if __name__ == '__main__':
    app.run(debug=True)